package com.ly.hotel.spainterface.jxd.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.NmSwipeCardUtils;
import com.ly.hotel.spainterface.OnSwipeCardInterface;
import com.ly.hotel.spainterface.nm.bean.XFBillBean;
import com.ly.hotel.util.IdChangeUtil;
import com.ly.hotel.util.InterfaceConfUtil;
import com.ly.hotel.view.RoundImageView;
import com.ly.hotel.webagent.UdpCallback;
import com.ly.hotel.webagent.UdpClient;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import de.greenrobot.event.EventBus;

/**
 * Created by SHUBEN on 2018/3/23.
 */

public class BillQuerySwipeDialog extends Dialog {
    private Context mcontext;
    private RoundImageView guestSwipe;
    private NmSwipeCardUtils swipUtils;
    private Button backBtn;
    private ImageView loading;
    private ImageView errBill;
    private TextView titleText;
    private Animation alphaAnimation;
    private Animation rotateAnimation;
    private MyApplication app;
    private double totalPrice = 0;
    private Handler handler;
    private String billAddMsg = null;

    public BillQuerySwipeDialog(Context context, int theme) {
        super(context, theme);
        mcontext = context;
        app = (MyApplication) mcontext.getApplicationContext();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bill_swipe_dialog);

        guestSwipe = findViewById(R.id.guest_swipe);
        backBtn = findViewById(R.id.dialog_back);
        loading = findViewById(R.id.guest_loading);
        titleText = findViewById(R.id.swip_title);
        errBill = findViewById(R.id.bill_error);
        alphaAnimation = AnimationUtils.loadAnimation(mcontext, R.anim.alpha_anim);
        rotateAnimation = AnimationUtils.loadAnimation(mcontext, R.anim.rotate_anim);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dismiss();
            }
        });

        handler = new Handler(){
            public void handleMessage(Message msg){
                loading.clearAnimation();
                switch (msg.what){
                    case 0:
                        titleText.setText(msg.obj.toString());
                        loading.setVisibility(View.GONE);
                        errBill.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        dismiss();
                        XFBillDialog billDialog = new XFBillDialog(mcontext,R.style.InputDialog, app.xfBillBeanList,totalPrice);
                        billDialog.setCanceledOnTouchOutside(true);
                        billDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                        billDialog.setAddMsg(billAddMsg);
                        billDialog.show();
                        EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                                MyApplication.interfaceVersion + "\t" + "账单查询"));
                        break;
                }
            }
        };
        swipUtils =  new NmSwipeCardUtils(new OnSwipeCardInterface() {
            @Override
            public void swipeCardListener(String cardId) {
                String newId = cardId.replaceAll("\r\n", "");
                if(newId.length() == 10) {
                    try {
                        long b = Long.parseLong(newId);
                        guestSwipe.clearAnimation();
                        titleText.setText("Loading...");
                        loading.setVisibility(View.VISIBLE);
                        guestSwipe.setVisibility(View.GONE);
                        loading.startAnimation(rotateAnimation);
                        toGetBillReq(newId);
                    } catch (NumberFormatException e) {
                        Log.e("swipe", "刷卡含有非法字符，重刷！");
                        swipUtils.initSwipe();
                    }
                }else{
                    Log.e("swipe", "刷卡不足10位，重刷！");
                    swipUtils.initSwipe();
                }
            }
        });
        initDialog();
    }

    public void initDialog(){
        titleText.setText(mcontext.getString(R.string.xf_swipe));
        loading.clearAnimation();
        guestSwipe.clearAnimation();
        errBill.setVisibility(View.GONE);
        loading.setVisibility(View.GONE);
        guestSwipe.setVisibility(View.VISIBLE);
        swipUtils.initSwipe();
        guestSwipe.startAnimation(alphaAnimation);
    }

    //分析接口类型查询账单
    private void toGetBillReq(String id){
        app.xfBillBeanList.clear();
        totalPrice = 0;
        if(MyApplication.interfaceVersion.contains("JXD")){
            String cardConf = InterfaceConfUtil.getConf("xiaofei","cardtype","ID_10");
            final String interfaceIp = InterfaceConfUtil.getConf("xiaofei","ip","172.16.1.205");
            final String interfacePort = InterfaceConfUtil.getConf("xiaofei","port","8081");
            final String cardId = IdChangeUtil.getId(id,cardConf);
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    final Message msg = new Message();
                    String request = "<gs ver=\"1.0\" function=\"桑拿帐单查询\" mode = \"request\">" +
                            "<RoomNo></RoomNo><KeyNo>" + cardId + "</KeyNo></gs>";

                    Log.d("udp", interfaceIp + "," + interfacePort + "," + request );
                    UdpCallback c = new UdpCallback() {
                        @Override
                        public void receive(String s) {
                            s =  s.replace("\r\n", "").replace("'", "’");
                            if(!TextUtils.isEmpty(s)) {
                                try {
                                    if (!s.startsWith("Msg")) {
                                        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
                                        DocumentBuilder dombuilder = domfac.newDocumentBuilder();
                                        Document doc = dombuilder.parse(new ByteArrayInputStream(s.getBytes("utf-8")));
                                        NodeList obj = doc.getElementsByTagName("gs");
                                        NodeList dataList = ((Element) obj.item(0)).getElementsByTagName("row");

                                        for (int i = 0; i < dataList.getLength(); i++) {
                                            NodeList keynoList = ((Element) dataList.item(i)).getElementsByTagName("keyno");
                                            NodeList nameList = ((Element) dataList.item(i)).getElementsByTagName("name");
                                            NodeList quantityList = ((Element) dataList.item(i)).getElementsByTagName("quantity");
                                            NodeList unitList = ((Element) dataList.item(i)).getElementsByTagName("unit");
                                            NodeList priceList = ((Element) dataList.item(i)).getElementsByTagName("price");
                                            NodeList typeList = ((Element) dataList.item(i)).getElementsByTagName("type");
                                            NodeList amountList = ((Element) dataList.item(i)).getElementsByTagName("amount");
                                            String keyno = "";
                                            String name = "";
                                            String unit = "";
                                            String price = "";
                                            String typeName = "";
                                            String quantity = "";
                                            String amount = "";
                                            if (keynoList.getLength() >= 1 && keynoList.item(0) != null && keynoList.item(0).hasChildNodes()) {
                                                keyno = keynoList.item(0).getFirstChild().getNodeValue();
                                            }

                                            if (nameList.getLength() >= 1 && nameList.item(0) != null && nameList.item(0).hasChildNodes()) {
                                                name = nameList.item(0).getFirstChild().getNodeValue();
                                            }

                                            if (quantityList.getLength() >= 1 && quantityList.item(0) != null && quantityList.item(0).hasChildNodes()) {
                                                quantity = quantityList.item(0).getFirstChild().getNodeValue();
                                                try{
                                                    quantity = String.format("%.0f",Double.parseDouble(quantity));
                                                }catch (NumberFormatException e){
                                                }
                                            }

                                            if (unitList.getLength() >= 1 && unitList.item(0) != null && unitList.item(0).hasChildNodes()) {
                                                unit = unitList.item(0).getFirstChild().getNodeValue();
                                            }
                                            if (priceList.getLength() >= 1 && priceList.item(0) != null && priceList.item(0).hasChildNodes()) {
                                                price = priceList.item(0).getFirstChild().getNodeValue();
                                            }
                                            if (typeList.getLength() >= 1 && typeList.item(0) != null && typeList.item(0).hasChildNodes()) {
                                                typeName = typeList.item(0).getFirstChild().getNodeValue();
                                            }

                                            if (amountList.getLength() >= 1 && amountList.item(0) != null && amountList.item(0).hasChildNodes()) {
                                                amount = amountList.item(0).getFirstChild().getNodeValue();
                                            }
                                            try {
                                                totalPrice += Double.parseDouble(amount);
                                            }catch (NumberFormatException e){
                                                Log.e("BillQuerySwipeDialog","账单转换出错");
                                            }
                                            XFBillBean bb = new XFBillBean();
                                            bb.setColumn1(keyno);
                                            bb.setColumn2(name);
                                            bb.setColumn3(typeName);
                                            bb.setColumn4(price);
                                            bb.setColumn5(quantity + unit);
                                            bb.setColumn6(amount);
                                            app.xfBillBeanList.add(bb);
                                        }
                                        msg.what=1;
                                        msg.obj = "ok";
                                    }else {
                                        msg.what=0;
                                        msg.obj = s;
                                    }
                                } catch (Exception e) {
                                    msg.what=0;
                                    msg.obj = "数据解析出错!";
                                }
                            }else {
                                msg.what=0;
                                msg.obj = mcontext.getString(R.string.connect_err);
                            }
                            handler.sendMessage(msg);
                        }
                    };
                    try {
                        int p = Integer.parseInt(interfacePort);
                        new UdpClient(interfaceIp, p, c, "<gs", "</gs>", "Msg").send(request);
                    } catch (NumberFormatException n) {
                        msg.what=0;
                        msg.obj = "配置出错";
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        msg.what=0;
                        msg.obj = "请求出错";
                        handler.sendMessage(msg);
                    }
                }
            }.start();
        }
    }

    @Override
    protected void onStop() {
        swipUtils.setOnSwipeFlag(false);
        super.onStop();
    }
}